<template>
  <div class="step1-container">
    <!-- 功能展示区 -->
    <div class="feature-section section-container">
      <div class="section-title">功能屏</div>
      <div class="button-group">
        <el-button class="feature-button" @click="showTotalFundRank">
          显示基金数总排名
        </el-button>
        <el-button class="feature-button" @click="showTotalFollowRank">
          显示关注数总排名
        </el-button>
        <el-button class="feature-button" @click="refreshFollowRankFunc">
          刷新关注数总排名
        </el-button>
        <el-button class="feature-button" @click="refreshFundRankFunc">
          刷新基金数总排名
        </el-button>
      </div>
    </div>

    <!-- 环形展示区 -->
    <div class="circle-section section-container">
      <div class="section-title">环形屏</div>
      <div class="button-group">
        <el-button class="circle-button" @click="switchToCountdown">
          切换为倒计时
        </el-button>
        <el-button class="circle-button" @click="switchToCelebrity">
          切换为红人信息
        </el-button>
      </div>
    </div>

    <!-- 移动端显示区 -->
    <div class="mobile-section section-container">
      <div class="section-title">移动端显示</div>
      <div class="button-group">
        <el-button class="mobile-button" @click="refreshMobileFund"
          >刷新移动端基金数</el-button
        >
      </div>
    </div>

    <!-- 操作区 -->
    <div class="operation-section section-container">
      <div class="section-title">操作</div>
      <div class="button-group">
        <el-button class="operation-button" @click="startActivity"
          >活动开始</el-button
        >
        <el-button class="operation-button" @click="endActivity"
          >活动结束</el-button
        >
        <el-button class="operation-button" @click="calculateFunds"
          >结算基金数</el-button
        >
        <el-button class="operation-button" @click="updateRank">晋级</el-button>
      </div>
    </div>

    <!-- 数据表格区 -->
    <div class="table-section">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="红人昵称">
          <template #default="scope">
            <div class="celebrity-cell">
              <el-tag size="small" type="warning" v-if="scope.row.tag">{{
                scope.row.tag
              }}</el-tag>
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fundCount" label="基金数"></el-table-column>
        <el-table-column prop="followCount" label="关注数"></el-table-column>
        <el-table-column prop="rank" label="晋级情况"></el-table-column>
        <el-table-column label="上传视频">
          <template #default="scope">
            <el-button size="small" @click="uploadVideo(scope.row)"
              >上传视频</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="syncFund" label="同步基金数">
          <template #default="scope">
            <el-tag size="small" type="success" v-if="scope.row.syncTag">{{
              scope.row.syncTag
            }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { editStatus, getStatusByCode } from "@/api/active";
import { listPlayer, updatePlayer, eliminatePlayer } from "@/api/player";

export default {
  name: "Step1",
  data() {
    return {
      totalFundRank: 0,
      totalFollowRank: 0,
      refreshFollowRank: 0,
      refreshFundRank: 0,
      timerPercentage: 75,
      countdownTime: "00:30:00",
      celebrityAvatar: "",
      celebrityName: "红人示例",
      tableData: [],
      activityId: "", // 当前活动ID
      timer: null, // 倒计时定时器
      isActivityStarted: false,
      showCountdown: true, // 控制显示倒计时还是红人信息
    };
  },
  created() {
    // 获取活动ID（假设从路由参数中获取）
    this.activityId = this.$route.params.id;
    // 初始化数据
    this.initData();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    async initData() {
      try {
        // 获取活动状态
        const status = await getStatusByCode(this.activityId);
        this.isActivityStarted = status.data;
        // 获取选手列表
        const players = await listPlayer({ activityId: this.activityId });
        this.tableData = players.data;
        // 更新排名数据
        this.updateRankings();
      } catch (error) {
        this.$message.error("初始化数据失败：" + error.message);
      }
    },
    updateRankings() {
      // 根据基金数排序
      const sortedByFund = [...this.tableData].sort(
        (a, b) => b.fundCount - a.fundCount
      );
      // 根据关注数排序
      const sortedByFollow = [...this.tableData].sort(
        (a, b) => b.followCount - a.followCount
      );

      this.totalFundRank = sortedByFund[0]?.fundCount || 0;
      this.totalFollowRank = sortedByFollow[0]?.followCount || 0;
    },
    startTimer() {
      const totalSeconds = 30 * 60; // 30分钟
      let remainingSeconds = totalSeconds;

      this.timer = setInterval(() => {
        remainingSeconds--;
        if (remainingSeconds <= 0) {
          clearInterval(this.timer);
          this.endActivity();
          return;
        }

        // 更新倒计时显示
        const minutes = Math.floor(remainingSeconds / 60);
        const seconds = remainingSeconds % 60;
        this.countdownTime = `${String(minutes).padStart(2, "0")}:${String(
          seconds
        ).padStart(2, "0")}:00`;
        this.timerPercentage = (remainingSeconds / totalSeconds) * 100;
      }, 1000);
    },
    async startActivity() {
      try {
        await editStatus(this.activityId, true);
        this.isActivityStarted = true;
        this.startTimer();
        this.$message.success("活动已开始");
      } catch (error) {
        this.$message.error("开始活动失败：" + error.message);
      }
    },
    async endActivity() {
      try {
        await editStatus(this.activityId, false);
        this.isActivityStarted = false;
        if (this.timer) {
          clearInterval(this.timer);
        }
        this.$message.success("活动已结束");
      } catch (error) {
        this.$message.error("结束活动失败：" + error.message);
      }
    },
    async calculateFunds() {
      try {
        // 获取前30名红人
        const top30 = [...this.tableData]
          .sort((a, b) => b.fundCount - a.fundCount)
          .slice(0, 30);

        // 更新这些红人的状态为"淘汰"
        for (const player of top30) {
          await eliminatePlayer(player.id);
        }

        // 刷新数据
        await this.initData();
        this.$message.success("基金数结算完成");
      } catch (error) {
        this.$message.error("结算基金数失败：" + error.message);
      }
    },
    async updateRank() {
      try {
        // 选择3个已淘汰的红人
        const eliminatedPlayers = this.tableData
          .filter((p) => p.status === "淘汰")
          .slice(0, 3);

        // 更新他们的状态
        for (const player of eliminatedPlayers) {
          await updatePlayer({
            ...player,
            status: "晋级",
            fundCount: 0,
          });
        }

        // 刷新数据
        await this.initData();
        this.$message.success("晋级更新完成");
      } catch (error) {
        this.$message.error("更新晋级状态失败：" + error.message);
      }
    },
    uploadVideo(row) {
      // 实现视频上传逻辑
      this.$message.info("视频上传功能待实现");
    },
    // 新增的功能展示区方法
    showTotalFundRank() {
      // 实现显示基金数总排名的逻辑
      this.initData();
    },
    showTotalFollowRank() {
      // 实现显示关注数总排名的逻辑
      this.initData();
    },
    refreshFollowRankFunc() {
      // 实现刷新关注数总排名的逻辑
      this.initData();
    },
    refreshFundRankFunc() {
      // 实现刷新基金数总排名的逻辑
      this.initData();
    },

    // 环形展示区方法
    switchToCountdown() {
      this.showCountdown = true;
    },
    switchToCelebrity() {
      this.showCountdown = false;
    },

    // 移动端显示区方法
    refreshMobileFund() {
      // 实现刷新移动端基金数的逻辑
      this.$message.success("移动端基金数已刷新");
    },
  },
};
</script>

<style lang="scss" scoped>
.step1-container {
  padding: 20px;

  .section-container {
    background: #f5f7fa;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 20px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 15px;
      padding-left: 10px;
      border-left: 4px solid #409eff;
    }

    .button-group {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .feature-button,
  .circle-button,
  .mobile-button,
  .operation-button {
    min-width: 160px;
    height: 40px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border: 1px solid #dcdfe6;
    margin: 0;
    padding: 0 15px;
    flex-grow: 0;

    &:hover {
      background: #ecf5ff;
      border-color: #409eff;
      color: #409eff;
    }

    .el-tag {
      margin-left: 8px;
    }
  }

  .feature-section,
  .circle-section,
  .mobile-section,
  .operation-section,
  .table-section {
    margin-bottom: 20px;
  }

  .feature-card,
  .circle-card {
    text-align: center;

    .card-title {
      font-size: 14px;
      color: #606266;
      margin-bottom: 10px;
    }

    .card-content {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
    }
  }

  .countdown-timer,
  .celebrity-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .timer-text {
      margin-top: 10px;
      font-size: 18px;
      font-weight: bold;
    }

    .info-text {
      margin-top: 10px;
      font-size: 16px;
    }
  }

  .celebrity-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}
</style>
